from django.core import serializers
from django.shortcuts import render, HttpResponse, render_to_response, redirect
from django.template import loader
from .models import TUser, TContract, TCategory, THouse
import json


# Create your views here.
def logout_view(request):
    del request.session['uname']
    return redirect('/')


def index_view(request):
    if request.session.get('uname', ''):
        uname = request.session['uname']
        return render(request, 'index.html', locals())
    return render(request, 'index.html')


def register_view(request):
    if request.method == 'GET':
        return render(request, 'register.html')
    else:
        uphone = request.POST['uphone']
        upwd = request.POST['upwd']
        uname = request.POST['uname']
        uemail = request.POST['uemail']
        category = request.POST.get('category', 2)
        user = TUser.objects.filter(uphone=uphone).first()
        if user:
            return HttpResponse('该用户已存在')
        try:
            TUser.objects.create(uname=uname, upwd=upwd, uemail=uemail, uphone=uphone, category=category, status=1)
            return redirect('/')
        except Exception as e:
            return HttpResponse(e)


def search_view(request):
    search_item = request.GET['searchItem']
    house_type = request.GET['houseType']
    if search_item:
        house = THouse.objects.filter(hname__icontains=search_item).all()
        data = serializers.serialize('json', house)
        return HttpResponse(data)
    if house_type:
        house = THouse.objects.filter(category=house_type).all()
        data = serializers.serialize('json', house)
        return HttpResponse(data)
    data = {
        'message': '没有相关搜索内容'
    }
    return HttpResponse(json.dumps(data))


def login_view(request):
    uphone = request.POST['uphone']
    upwd = request.POST['upassword']
    user = TUser.objects.filter(uphone=uphone).first()
    if user:
        # 判断密码是否正确
        if user.upwd == upwd:
            request.session['uname'] = user.uname
            request.session['id'] = user.id
            data = {
                'code': 3,
                'message': '登陆成功，正在跳转'
            }
            return HttpResponse(json.dumps(data))
        data = {
            'code': 2,
            'message': '输入的密码错误'
        }
        return HttpResponse(json.dumps(data))
    data = {
        'code': 1,
        'message': '该用户不存在'
    }
    return HttpResponse(json.dumps(data))


def contract_view(request):
    uname = request.session['uname']
    if request.GET.get('contractId', ''):
        cid = request.GET.get('contractId')
        contract = TContract.objects.filter(id=cid).first()
        landlord = TUser.objects.filter(id=contract.lid).first()
        tenant = TUser.objects.filter(id=contract.tid).first()
        return render(request, 'contract.html', locals())
    tenant = TUser.objects.filter(uname=uname).first()
    return render(request, 'contract.html', locals())


def get_contract(request):
    contract_id = request.GET.get('contractId', '')
    if contract_id:
        contract_data = TContract.objects.filter(id=contract_id).first()
        if contract_data:
            tenant = TUser.objects.filter(id=contract_data.lid).first()
            landlord = TUser.objects.filter(id=contract_data.tid).first()
            response_data = {
                'contractId': contract_data.id,
                'price': contract_data.price,
                'tenant': tenant.uname,
                'landlord': landlord.uname
            }
            template = loader.get_template('contract.html')
            context = {'data': response_data}
            return HttpResponse(template.render(context))
        return HttpResponse("该合同不存在")
    return HttpResponse('请输入正确的合同编号')


def person_view(request):
    uname = request.session['uname']
    tenant = TUser.objects.filter(uname=uname).first()
    return render(request, 'person.html', locals())


def chagne_name(request):
    new_name = request.GET.get('newName', '')
    if new_name:
        user_id = request.session['id']
        user = TUser.objects.filter(id=user_id).update(uname=new_name)
        request.session['uname'] = new_name
        return redirect('/person')
    return HttpResponse("请输入正确的昵称")


def change_pwd(request):
    old_pwd = request.GET.get('oldPwd', '')
    new_pwd = request.GET.get('newPwd', '')
    user_id = request.session['id']
    user = TUser.objects.filter(id=user_id).first()
    if user.upwd == old_pwd:
        TUser.objects.filter(id=user_id).update(upwd=new_pwd)
        return HttpResponse("<h1 aligin='center'>修改密码成功</h1><a href='#'>跳转至登录页</a>")
    return HttpResponse("<h1 aligin='center'>原密码输入错误！</h1><a href='#'>返回</a>")


def change_phone(request):
    uphone = request.GET.get('newPhone', '')
    user_id = request.session['id']
    user = TUser.objects.filter(id=user_id).update(uphone=uphone)
    if user:
        return HttpResponse("手机号修改成功")
    return HttpResponse("手机号修改失败")


def followhouse_view(request):
    uname = request.session['uname']
    tenant = TUser.objects.filter(uname=uname).first()
    return render(request, 'followhouse.html', locals())


def get_house_type_api(request):
    categories = TCategory.objects.all()
    # data = json.dumps(list(categories))
    data = serializers.serialize('json', categories)
    return HttpResponse(data)


def search_more_api(request):
    house_name = request.GET['houseName']
    house = THouse.objects.filter(hname=house_name).first()
    user = TUser.objects.filter(uname=house.uid).first()
    print(user.header)
    if request.session.get('uname', ''):
        uname = request.session['uname']
        return render(request, 'house.html', locals())
    return render(request, 'house.html', locals())


def attention_house_api(request):
    house_name = request.GET['houseName']
    if request.session.get('uname', ''):
        uname = request.session['uname']
        TUser.objects.filter(uname=uname).update(house=house_name)
        data = {
            'message': '关注房源成功'
        }
        return HttpResponse(json.dumps(data))
    data = {
        'message': '关注房源失败，请先登陆'
    }
    return HttpResponse(json.dumps(data))


def order_house_api(request):
    house_name = request.GET['houseName']
    if request.session.get('uname', ''):
        uname = request.session['uname']
        TUser.objects.filter(uname=uname).update(house=house_name)
        data = {
            'code': 1,
        }
        return HttpResponse(json.dumps(data))
    data = {
        'code': 2,
        'message': '订购失败，请先登陆'
    }
    return HttpResponse(json.dumps(data))


def order_house_html_api(request):
    house_name = request.GET['houseName']
    if request.session.get('uname', ''):
        # 租房者
        uname = request.session['uname']
        house = THouse.objects.filter(hname=house_name).first()
        # 出租者
        landlord = house.uid
        landlord = TUser.objects.filter(uname=landlord).first()
        return render(request, 'orderHouse.html', locals())
    return HttpResponse('<h1>404</h1>')


def generate_contract_api(request):
    valid_to = request.GET['valid']
    price = request.GET['price']
    landlord = request.GET['lname']
    landlord = TUser.objects.filter(uname=landlord).first()
    tid = request.session.get('id', '')
    TContract.objects.create(value_to=valid_to, price=price, lid=landlord.id, tid=tid)
    data = {
        'code': 1,
        'message': '订购成功, 正在跳转，请稍等'
    }
    return HttpResponse(json.dumps(data))

